#include "App.h"
#include "LogModule.h"
#include "MinuteTimer.h"
#include "NetworkModule.h"
#include "PipeManager.h"
//#include "ProtoMgr.h"
#include "TimerMgr.h"
#include <ut_debug.h>
#include "GateServer.h"

static int g_bTerminated = false;
#ifdef WIN32
#include <Windows.h>
BOOL WINAPI console_handler(DWORD cevent)
{
    switch(cevent)
    {
    case CTRL_C_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_CLOSE_EVENT:
    case CTRL_LOGOFF_EVENT:
    case CTRL_SHUTDOWN_EVENT:
        {
            //your code here
            g_bTerminated = true;
            break;
        }
    default:
        {
        }
    }
    return TRUE;
};
#else
void term_handler(int sig)
{
    g_bTerminated = true;

}
#endif

CDBServerApp::CDBServerApp( void )
{
    CLogModule::Instance();
    CGateServerMgr::Instance();
    CMinuteTimer::Instance();
    CTimerMgr::Instance();
    //CProtoMgr::Instance();
    CPipeManager::Instance();
    CNetworkModule::Instance();
}

CDBServerApp::~CDBServerApp( void )
{
    CLogModule::DestroyInstance();
    CGateServerMgr::DestroyInstance();
    CMinuteTimer::DestroyInstance();
    CTimerMgr::DestroyInstance();
    //CProtoMgr::DestroyInstance();
    CPipeManager::DestroyInstance();
    CNetworkModule::DestroyInstance();
}

void CDBServerApp::Run()
{
    if (_Init())
    {
        while(!g_bTerminated)
        {
            bool bBusy = false;

            bBusy |= CNetworkModule::Instance()->Run();
            bBusy |= CTimerMgr::Instance()->Run();
            if (!bBusy)
                Sleep(1);
        }
    }
}

bool CDBServerApp::_Init()
{
#ifdef WIN32
    if (SetConsoleCtrlHandler( (PHANDLER_ROUTINE)console_handler,TRUE)==FALSE)
    {
        return false;
    }
#else
    signal(SIGTERM,term_handler) ;
    signal(SIGINT,term_handler) ;
    signal(SIGUSR2,term_handler) ;
    signal(SIGALRM,SIG_IGN);
#endif

    if (!CLogModule::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initializing log module";
        return false;
    }

    if (!CNetworkModule::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initializing network module";
        return false;
    }

    if (!CTimerMgr::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initializing timer manager";
        return false;
    }

    LOG(INFO) << "Initialize successfully";

    return true;
}
